package com.eis.admin.mvc.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.eis.admin.mvc.bean.xml.ConnectorConfigureBean;
import com.eis.admin.mvc.common.utils.MVCConstants;
import com.eis.admin.mvc.controller.base.MVCBaseController;
import com.eis.exception.EisSysException;
import com.eis.persist.dao.BizSystemDAO;
import com.eis.persist.dao.impl.BizSystemDAOImpl;
import com.eis.persist.model.bizsystem.PersistBizSystem;
import com.eis.persist.model.bizsystem.PersistConnectorConfigure;
import com.eis.persist.model.user.PersistUser;
import com.eis.thirdsys.connector.ThirdSysConnectorFactory;
import com.eis.thirdsys.connector.conf.bean.ConfParameterName;
import com.eis.util.XmlUtil;

@Controller
public class BizSystemAdminController extends MVCBaseController {
	private static final Logger logger = LoggerFactory
			.getLogger(BizSystemAdminController.class);
	private BizSystemDAO bizSystemLoadDAO;
	private XmlUtil xmlUtil;
	public void setXmlUtil(XmlUtil xmlUtil) {
		this.xmlUtil = xmlUtil;
	}

	@Override
	public void setFunctionDataSource(JdbcTemplate functionDataSource) {
		this.functionDataSource = functionDataSource;
		bizSystemLoadDAO = new BizSystemDAOImpl(this.functionDataSource);
	}
	
	@RequestMapping(value = "/bizsysIntroduction")
	public ModelAndView functionIntroduction(Model model, HttpServletRequest request) {
		return new ModelAndView("/function/bizsysIntroduction");
	}

	@RequestMapping(value = "/bizSystemList")
	public ModelAndView bizSystemList(Model model, HttpServletRequest request) {
		PersistUser currentUser = (PersistUser) request.getSession().getAttribute(
				MVCConstants.USER_SESSION_KEY);
		BizSystemDAO bizSystemDAO = new BizSystemDAOImpl(this.functionDataSource, currentUser.getName());
		List<PersistBizSystem> bizSystemList = bizSystemDAO.getAllBizSystems();
		model.addAttribute("bizSystemList", bizSystemList);
		
		return new ModelAndView("/function/bizSystemList", "command", new PersistBizSystem());
	}
	
	@RequestMapping(value = "/addBizSystem")
	public ModelAndView addBizSystem(@ModelAttribute("addBizSystem") PersistBizSystem bizSystem, Model model, HttpServletRequest request) {
		PersistUser currentUser = (PersistUser) request.getSession().getAttribute(
				MVCConstants.USER_SESSION_KEY);
		BizSystemDAO bizSystemDAO = new BizSystemDAOImpl(this.functionDataSource, currentUser.getName());
		String message = "Operation done";
		try {
			bizSystemDAO.saveBizSystem(bizSystem);
			return new ModelAndView(
					"redirect:" + appPrefix + "/bizSystemList",
					prepareRedirectWarnMessage(message));
		} catch (EisSysException e) {
			message = e.getErrorCode() + ", " + e.getMessage();
			return new ModelAndView(
					"redirect:" + appPrefix + "/bizSystemList",
					prepareRedirectErrorMessage(message));
		}
	}
	
	@RequestMapping(value = "/connectorConfigures")
	public ModelAndView connectorConfigures(Model model, HttpServletRequest request) {
		PersistUser currentUser = (PersistUser) request.getSession().getAttribute(
				MVCConstants.USER_SESSION_KEY);
		BizSystemDAO bizSystemDAO = new BizSystemDAOImpl(this.functionDataSource, currentUser.getName());

		// get bizsysid from request
		int bizSysId = 0;
		try {bizSysId = Integer.valueOf(request.getParameter("bizsysid"));} catch (Throwable t) {}
		
		if (bizSysId > 0) {
			// load BizSystem
			PersistBizSystem system = bizSystemDAO.getBizSystem(bizSysId);
			if (system != null) {
				List<PersistConnectorConfigure> connectorConfigList = bizSystemDAO.getConnectorConfigs(bizSysId);
				// convert to display
				List<ConnectorConfigureBean> connectorConfigDisplayList = new ArrayList<ConnectorConfigureBean>();
				List<ConfParameterName> parameterNameList = new ArrayList<ConfParameterName>();
				try {
					ThirdSysConnectorFactory thirdSysConnectorFactory = new ThirdSysConnectorFactory(system.getConnectorStaticsClassName());
					parameterNameList = thirdSysConnectorFactory.getConnectorStatics().getConfParameterNames();
					
					if (connectorConfigList != null && connectorConfigList.size() > 0) {
						for (PersistConnectorConfigure pconfig : connectorConfigList) {
							ConnectorConfigureBean parsed = (ConnectorConfigureBean) xmlUtil.parseXml(pconfig.getConfigXml());
							parsed.setConnectorname(pconfig.getName());
							parsed.setConnectorId(pconfig.getId());
							connectorConfigDisplayList.add(parsed);
						}
					}
				} catch (Exception e) {
					logger.error("Oh GOD!", e);
				} 
				model.addAttribute("connectorConfigLabelList", parameterNameList);
				model.addAttribute("connectorConfigList", connectorConfigDisplayList);
				return new ModelAndView("/function/connectorConfigureList", "command", system);
			}
		}
		
		List<PersistBizSystem> bizSystemList = bizSystemDAO.getAllBizSystems();
		model.addAttribute("bizSystemList", bizSystemList);
		model.addAttribute("targetpath", "connectorConfigures");
		
		return new ModelAndView("/function/selectBizsys1", "command", new PersistBizSystem());
	}
	
	@RequestMapping(value = "/addConnectorConfigure")
	public ModelAndView addConnectorConfigure(@ModelAttribute("addConnectorConfigure") ConnectorConfigureBean connectorConfigure, Model model, HttpServletRequest request) {
		PersistUser currentUser = (PersistUser) request.getSession().getAttribute(
				MVCConstants.USER_SESSION_KEY);
		BizSystemDAO bizSystemDAO = new BizSystemDAOImpl(this.functionDataSource, currentUser.getName());
		String message = "Operation done";

		try {
			PersistConnectorConfigure persistConnectorConfigure = new PersistConnectorConfigure();
			PersistBizSystem persistBizSystem = new PersistBizSystem();
			persistBizSystem.setId(connectorConfigure.getBizsysid());
			persistConnectorConfigure.setBizSystem(persistBizSystem);
			persistConnectorConfigure.setConfigXml(xmlUtil.toXml(connectorConfigure));
			persistConnectorConfigure.setName(connectorConfigure.getConnectorname());
			
			bizSystemDAO.saveConnectorConfigure(persistConnectorConfigure);
			return new ModelAndView(
					"redirect:" + appPrefix + "/connectorConfigures?bizsysid=" + connectorConfigure.getBizsysid(),
					prepareRedirectWarnMessage(message));
		} catch (EisSysException e) {
			message = e.getErrorCode() + ", " + e.getMessage();
			return new ModelAndView(
					"redirect:" + appPrefix + "/connectorConfigures?bizsysid=" + connectorConfigure.getBizsysid(),
					prepareRedirectErrorMessage(message));
		}
	}

	@RequestMapping(value = "/editBizSystem")
	public ModelAndView editBizSystem(Model model, HttpServletRequest request) {
		// PersistUser currentUser = (PersistUser) request.getSession().getAttribute(MVCConstants.USER_SESSION_KEY);
		// get bizsysid from request
		int bizSysId = 0;
		try {
			bizSysId = Integer.valueOf(request.getParameter("bizsysId"));
		} catch (Throwable t) {}
		
		if (bizSysId > 0) {
			// load BizSystem
			PersistBizSystem system = bizSystemLoadDAO.getBizSystem(bizSysId);
			
			if (system != null) {
				return new ModelAndView("/function/editBusinessSystem", "command", system);
			}
		}
		return new ModelAndView("commonError");
		
	}
	
	@RequestMapping(value = "/submiteditBizSystem")
	public ModelAndView submiteditBizSystem(@ModelAttribute("editBizSystemform") PersistBizSystem editSystem, Model model, HttpServletRequest request) {
		PersistUser currentUser = (PersistUser) request.getSession().getAttribute(
				MVCConstants.USER_SESSION_KEY);
		// get bizsysid from request
		int bizSysId = editSystem.getId();
		String message = "Operation done";
		if (bizSysId > 0) {
			// load BizSystem
			try {
				BizSystemDAO dao = new BizSystemDAOImpl(functionDataSource, currentUser.getName());
				dao.saveBizSystem(editSystem);
				return new ModelAndView(
						"redirect:" + appPrefix + "/bizSystemList",
						prepareRedirectWarnMessage(message));
			} catch (EisSysException e) {
				message = e.getErrorCode() + ", " + e.getMessage();
				return new ModelAndView(
						"redirect:" + appPrefix + "/bizSystemList",
						prepareRedirectErrorMessage(message));
			}
		}
		message = "The Business System you tried to edit doesn't exist.";
		return new ModelAndView(
				"redirect:" + appPrefix + "/bizSystemList",
				prepareRedirectErrorMessage(message));
		
	}
	
	@RequestMapping(value = "/deleteConnectorConfig")
	public ModelAndView deleteConnectorConfig(Model model, HttpServletRequest request) {
		PersistUser currentUser = (PersistUser) request.getSession().getAttribute(
				MVCConstants.USER_SESSION_KEY);
		// get bizsysid from request
		int bizSysId = 0;
		int connectorConfigId = 0;
		try {
			bizSysId = Integer.valueOf(request.getParameter("bizsysId"));
			connectorConfigId = Integer.valueOf(request.getParameter("connectorConfigId"));
		} catch (Throwable t) {
		}
		String message = "Operation done";
		if (bizSysId > 0) {
			// load BizSystem
			try {
				BizSystemDAO dao = new BizSystemDAOImpl(functionDataSource, currentUser.getName());
				dao.deleteConnectorConfigure(connectorConfigId);
				
				return new ModelAndView(
						"redirect:" + appPrefix + "/connectorConfigures?bizsysid=" + bizSysId,
						prepareRedirectWarnMessage(message));
			} catch (EisSysException e) {
				message = e.getErrorCode() + ", " + e.getMessage();
				return new ModelAndView(
						"redirect:" + appPrefix + "/connectorConfigures?bizsysid=" + bizSysId,
						prepareRedirectErrorMessage(message));
			}
		}
		
		message = "The Connector Configure you tried to edit doesn't exist.";
		return new ModelAndView(
				"redirect:" + appPrefix + "/connectorConfigures?bizsysid=" + bizSysId,
				prepareRedirectErrorMessage(message));
		
	}
}
